<template>
    <div>
        <div>
            <label for="search">查询：</label>
            <input type="text" id="search" v-model="searchQuery" placeholder="输入查询内容" class="search-input" />
            <button @click="recordNumber" class="search-button">用户录入数量可视化</button>
            <button @click="dateRecordNumber" class="search-button2">录入日期数量可视化</button>
        </div>
        <table>
            <thead>
                <tr>
                    <!-- 动态生成表头 -->
                    <th v-for="column in displayColumns" :key="column">{{ column }}</th>
                </tr>
            </thead>
            <tbody>
                <!-- 循环渲染表格行 -->
                <tr v-for="(row, rowIndex) in paginatedData" :key="rowIndex">
                    <td v-for="(value, colIndex) in row.slice(0, 3)" :key="colIndex">{{ value }}</td>
                    <td>
                        <button @click="handleDelete(row[0])" class="delete-button">删除</button>
                        <button @click="editRow(rowIndex)" class="modify-button">修改</button>
                    </td>
                </tr>
            </tbody>
        </table>
        <!-- 分页组件 -->
        <el-locale-provider :locale="locale">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[10, 20, 30, 40]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="filteredInvoiceData.length"
                :page-count="Math.ceil(filteredInvoiceData.length / pageSize)"
                :pager-count="5"
                :popper-class="'pagination-popper'"
                total-text="共 {{ filteredInvoiceData.length }} 条"
                prev-text="上一页"
                next-text="下一页"
                jumper-text="跳到"
                :background="true"
                style="text-align: right; margin-top: 20px;"
            >
            </el-pagination>
        </el-locale-provider>
        <!-- 可视化图表容器 -->
        <div v-if="showChart" id="chart" style="width: 100%; height: 400px;"></div>
    </div>
</template>

<script>
import zhCn from 'element-plus/es/locale/lang/zh-cn';
import axios from 'axios'; // 引入 axios
import * as echarts from 'echarts'; // 引入 ECharts

export default {
    data() {
        return {
            invoiceData: [],
            displayColumns: ['发票编号', '录入用户名', '录入日期', '操作'],
            currentPage: 1,
            pageSize: 10,
            searchQuery: '', // 查询条件
            filteredInvoiceData: [], // 过滤后的数据
            paginatedData: [], // 分页后的数据
            showChart: false // 控制图表是否显示
        };
    },
    created() {
        this.fetchInvoices();
    },
    methods: {
        async fetchInvoices() {
            try {
                const response = await axios.get('http://127.0.0.1:5000/api/record_data'); // 使用 axios 替换 fetch
                this.invoiceData = response.data;
                this.filterData(); // 初始加载时也进行过滤
            } catch (error) {
                console.error('Failed to fetch invoices:', error);
            }
        },
        handleDelete(no) {
            const shouldDelete = window.confirm('您是否要删除？');
            if (shouldDelete) {
                this.deleteRow(no);
            }
        },
        deleteRow(no) {
            console.log("要发送的 No 值:", no);  // 添加这行日志
            // 向后端发送删除请求
            axios.post('http://127.0.0.1:5000/api/delete_record', { no })
              .then(response => {
                    if (response.data.success) {
                        // 如果删除成功，重新获取数据
                        this.fetchInvoices();
                    } else {
                        console.error('删除失败:', response.data.message);
                    }
                })
              .catch(error => {
                    console.error('删除请求出错:', error);
                });
        },
        editRow(index) {
            // 这里应实现与后端交互以进行修改操作
            // 示例：仅在控制台输出要修改的行索引
            console.log('修改第', index, '行');
        },
        handleSizeChange(newSize) {
            this.pageSize = newSize;
            this.paginateData();
        },
        handleCurrentChange(newPage) {
            this.currentPage = newPage;
            this.paginateData();
        },
        filterData() {
            // 根据查询条件过滤数据
            if (!this.searchQuery) {
                this.filteredInvoiceData = this.invoiceData; // 如果没有查询条件，显示全部数据
            } else {
                const query = this.searchQuery.toLowerCase();
                this.filteredInvoiceData = this.invoiceData.filter(row => {
                    // 检查每一行的每个字段是否包含查询内容
                    return row.some(value => {
                        return String(value).toLowerCase().includes(query);
                    });
                });
            }
            this.paginateData();
        },
        paginateData() {
            const startIndex = (this.currentPage - 1) * this.pageSize;
            const endIndex = startIndex + this.pageSize;
            this.paginatedData = this.filteredInvoiceData.slice(startIndex, endIndex);
        },
        recordNumber() {
            this.showChart = true;
            this.$nextTick(() => {
                // 统计每个录入用户名的发票数量
                const userCountMap = {};
                this.invoiceData.forEach(row => {
                    const username = row[1];
                    if (userCountMap[username]) {
                        userCountMap[username]++;
                    } else {
                        userCountMap[username] = 1;
                    }
                });
                // 将统计结果转换为数组并按录入数量从高到低排序
                const userCountArray = Object.entries(userCountMap).sort((a, b) => b[1] - a[1]);
                const usernames = userCountArray.map(item => item[0]);
                const counts = userCountArray.map(item => item[1]);

                // 初始化 ECharts 实例
                const chartDom = document.getElementById('chart');
                const myChart = echarts.init(chartDom);
                const option = {
                    xAxis: {
                        type: 'category',
                        data: usernames,
                        axisLabel: {
                            rotate: 45, // 横坐标标签旋转 45 度，避免标签重叠
                            interval: 0 // 强制显示所有标签
                        }
                    },
                    yAxis: {
                        type: 'value',
                        minInterval: 1 // 设置 Y 轴单位间隔为 1
                    },
                    series: [{
                        data: counts,
                        type: 'bar'
                    }]
                };
                // 使用刚指定的配置项和数据显示图表。
                myChart.setOption(option);
            });
        },
        dateRecordNumber() {
            this.showChart = true;
            this.$nextTick(() => {
                // 统计每个录入日期的发票数量
                const dateCountMap = {};
                this.invoiceData.forEach(row => {
                    const date = row[2];
                    if (dateCountMap[date]) {
                        dateCountMap[date]++;
                    } else {
                        dateCountMap[date] = 1;
                    }
                });
                // 将统计结果转换为数组并按日期排序
                const dateCountArray = Object.entries(dateCountMap).sort((a, b) => new Date(a[0]) - new Date(b[0]));
                const dates = dateCountArray.map(item => item[0]);
                const counts = dateCountArray.map(item => item[1]);

                // 初始化 ECharts 实例
                const chartDom = document.getElementById('chart');
                const myChart = echarts.init(chartDom);
                const option = {
                    xAxis: {
                        type: 'category',
                        data: dates,
                        axisLabel: {
                            rotate: 45, // 横坐标标签旋转 45 度，避免标签重叠
                            interval: 0 // 强制显示所有标签
                        }
                    },
                    yAxis: {
                        type: 'value',
                        minInterval: 1 // 设置 Y 轴单位间隔为 1
                    },
                    series: [{
                        data: counts,
                        type: 'bar'
                    }]
                };
                // 使用刚指定的配置项和数据显示图表。
                myChart.setOption(option);
            });
        }
    },
    watch: {
        // 监听搜索框内容变化，实时过滤数据
        searchQuery(newQuery) {
            this.filterData();
        }
    }
};
</script>

<style scoped>
table {
    width: 100%;
    border-collapse: collapse;
}

th,
td {
    border: 1px solid #ccc;
    padding: 8px;
    text-align: left;
}

th {
    background-color: #f2f2f2;
}

.delete-button {
    background-color: #e9120a;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 5px;
    cursor: pointer;
    margin-left: 10px;
}

.modify-button {
    background-color: #4273b3;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 5px;
    cursor: pointer;
    margin-left: 10px;
}

.search-input {
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    margin-right: 10px;
    font-size: 14px;
    width: 300px; /* 可以根据需要调整宽度 */
}

.search-button {
    background-color: #28a745;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 5px;
    cursor: pointer;
    font-size: 14px;
    margin-left: 10px; /* 添加左边距，让按钮之间有间距 */
}

.search-button2 {
    background-color: #4fa3cd;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 5px;
    cursor: pointer;
    font-size: 14px;
    margin-left: 10px; /* 添加左边距，让按钮之间有间距 */
}
</style>    